<template>
  <div class="register">
    <h2>注册</h2>
    <form @submit.prevent="handleRegister" class="register-form">
      <div class="form-item">
        <label>用户名：</label>
        <input type="text" v-model="username" required />
      </div>
      <div class="form-item">
        <label>密码：</label>
        <input type="password" v-model="password" required />
      </div>
      <div class="form-item">
        <label>确认密码：</label>
        <input type="password" v-model="confirmPassword" required />
      </div>
      <button type="submit">注册</button>
    </form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const username = ref('')
const password = ref('')
const confirmPassword = ref('')

const handleRegister = async () => {
  if (password.value !== confirmPassword.value) {
    alert('两次输入的密码不一致')
    return
  }

  try {
    await axios.post('/api/user/register', {
      username: username.value,
      password: password.value
    })
    alert('注册成功')
    router.push('/login')
  } catch (error) {
    alert('注册失败')
  }
}
</script>

<style scoped>
.register {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}

.register-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

input {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  padding: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style> 